package UDP;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UDPServerDemo {
    public static void main(String[] args) throws IOException {
        //目标,完成UDP通信一发一收,服务端开发
        //1.创建一个接收端对象,注册端口
        DatagramSocket socket=new DatagramSocket(8080);
        //2.创建数据包对象负责接收数据(韭菜盒子)
        byte[]buf=new byte[1027*64];
        DatagramPacket packet=new DatagramPacket(buf,buf.length);

        //3.接收数据,将数据封装到数据包对象的字节数组中去
        socket.receive((packet));

        //4.看数据是否收到
        //获取当前数据长度
        int len=packet.getLength();
        String data=new String(buf,0,len);
        System.out.println("服务器收到了"+data);

        //获取对方ip对象和程序端口
        String ip=packet.getAddress().getHostAddress();
        int port=packet.getPort();
        System.out.println("对方ip"+ip+"对方端口"+port);
    }
}
